import React, {useEffect, useState} from 'react';
import {Table, Progress, Button} from 'antd';
import {ExclamationCircleFilled} from '@ant-design/icons';
import {withRouter} from 'react-router-dom';

import {personalSearch, fetchPersonalDownload} from '~/service/renew';
import {parsePercent} from '~/utils/number';
import {getReportRounds} from '~/utils/menu';
import {buildTip} from '../common';
import './index.styl';

const rateRender = rate => (
    <span className="rate">
        {Number.isNaN(parseFloat(rate)) ? '-' : parsePercent(rate, 2)}
    </span>
);

const renderNum = text => (
    <div className="personal-table-text">
        {text || 0}
    </div>
);

const renderText = text => (
    <div className="personal-table-text">
        {text}
    </div>
);

const progressRender = text => (
    <div style={{position: 'relative'}} className="department-progess">
        <span style={{position: 'absolute', left: 8, top: '10%', zIndex: 1}}>{parsePercent(text, 2)}</span>
        <Progress
            strokeWidth={30}
            showInfo={false}
            percent={parseFloat(parsePercent(text, 2))}
            size="small"
            strokeColor="#1890ff"
        />
        {/* {text} */}
    </div>
);

// 根据一轮二轮 获取不同的列展示
const columsByUserRound = (userRoundValue, namePrev, [dataIndex1, dataIndex2], render) => {
    // 1 一轮 2 二轮
    if (userRoundValue === 2) {
        return ([
            {
                title: `${namePrev}-插1学员`,
                dataIndex: dataIndex1 || 'smallRank',
                render
            },
            {
                title: `${namePrev}-插2学员`,
                dataIndex: dataIndex2 || 'smallRank',
                render
            }
        ]);
    }
    return [];
};

const columnsFn = userRoundValue => (
    [
        {
            title: '小组排名',
            dataIndex: 'smallRank',
            width: 90,
            fixed: 'left',
            render: renderText
        },
        {
            title: '大组排名',
            dataIndex: 'bigRank',
            width: 90,
            fixed: 'left',
            render: renderText
        },
        {
            title: '学部排名',
            dataIndex: 'departmentRank',
            width: 90,
            fixed: 'left',
            render: renderText
        },
        {
            title: '辅导老师',
            dataIndex: 'employeeName',
            width: 100,
            fixed: 'left',
            render: renderText
        },
        {
            title: '小组长',
            dataIndex: 'directLeaderName',
            render: renderText
        },
        {
            title: '大组长',
            dataIndex: 'leaderName',
            render: renderText
        },
        {
            title: '学部',
            dataIndex: 'department',
            render: renderText
        },
        {
            title: '中心',
            dataIndex: 'area',
            render: renderText
        },
        {
            title: '年级',
            dataIndex: 'grade',
            render: renderText
        },
        {
            title: '学科',
            dataIndex: 'subject',
            render: renderText
        },
        {
            title: '可续人数-整体',
            dataIndex: 'canRenewalNum',
            render: renderNum
        },
        {
            title: '可续人数-新学员',
            dataIndex: 'canRenewalNumNew',
            render: renderNum
        },
        {
            title: '可续人数-老学员',
            dataIndex: 'canRenewalNumOld',
            render: renderNum
        },
        ...columsByUserRound(userRoundValue, '可续人数', ['canRenewalNumLate1', 'canRenewalNumLate2'], renderNum),
        {
            title: '综合续班率-整体',
            dataIndex: 'comprehensiveRatio',
            render: rateRender

        },
        {
            title: '综合续班率-新学员',
            dataIndex: 'comprehensiveRatioNew',
            render: rateRender

        },
        {
            title: '综合续班率-老学员',
            dataIndex: 'comprehensiveRatioOld',
            render: rateRender
        },
        ...columsByUserRound(
            userRoundValue,
            '综合续班率',
            ['comprehensiveRatioLate1', 'comprehensiveRatioLate2'],
            rateRender
        ),
        {
            title: '综续目标达成率-整体',
            dataIndex: 'targetRatio',
            align: 'center',
            render: progressRender
        },
        {
            title: '综续目标达成率-新学员',
            dataIndex: 'targetRatioNew',
            align: 'center',
            render: progressRender
        },
        {
            title: '综续目标达成率-老学员',
            dataIndex: 'targetRatioOld',
            align: 'center',
            render: progressRender
        },
        ...columsByUserRound(userRoundValue, '综续目标达成率', ['targetRatioLate1', 'targetRatioLate2'], progressRender),
        {
            title: '综续目标-整体',
            dataIndex: 'comprehensiveTargetRatio',
            render: rateRender
        },
        {
            title: '综续目标-新学员',
            dataIndex: 'comprehensiveTargetRatioNew',
            render: rateRender
        },
        {
            title: '综续目标-老学员',
            dataIndex: 'comprehensiveTargetRatioOld',
            render: rateRender
        },
        ...columsByUserRound(
            userRoundValue,
            '综续目标',
            ['comprehensiveTargetRatioLate1', 'comprehensiveTargetRatioLate2'],
            rateRender
        ),
        {
            title: '综合续班率-今日新增',
            dataIndex: 'todayIncrease',
            render: rateRender
        },
        {
            title: '纯续班率-整体',
            dataIndex: 'renewalRatio',
            render: rateRender

        },
        {
            title: '纯续班率-新学员',
            dataIndex: 'renewalRatioNew',
            render: rateRender

        },
        {
            title: '纯续班率-老学员',
            dataIndex: 'renewalRatioOld',
            render: rateRender

        },
        ...columsByUserRound(userRoundValue, '纯续班率', ['renewalRatioLate1', 'renewalRatioLate2'], rateRender),
        {
            title: '纯续目标达成率-整体',
            dataIndex: 'renewalTargetCompletionRatio',
            align: 'center',
            render: progressRender
        },
        {
            title: '纯续目标达成率-新学员',
            dataIndex: 'renewalTargetCompletionRatioNew',
            align: 'center',
            render: progressRender
        },
        {
            title: '纯续目标达成率-老学员',
            dataIndex: 'renewalTargetCompletionRatioOld',
            align: 'center',
            render: progressRender
        },
        ...columsByUserRound(
            userRoundValue,
            '纯续目标达成率',
            ['renewalTargetCompletionRatioLate1', 'renewalTargetCompletionRatioLate2'],
            progressRender
        ),
        {
            title: '纯续目标-整体',
            dataIndex: 'renewalTargetRatio',
            render: rateRender
        },
        {
            title: '纯续目标-新学员',
            dataIndex: 'renewalTargetRatioNew',
            render: rateRender
        },
        {
            title: '纯续目标-老学员',
            dataIndex: 'renewalTargetRatioOld',
            render: rateRender
        },
        ...columsByUserRound(
            userRoundValue,
            '纯续目标',
            ['renewalTargetRatioLate1', 'renewalTargetRatioLate2'],
            rateRender
        ),
        {
            title: '扩科率',
            dataIndex: 'extendRatio',
            render: rateRender
        },
        {
            title: '转介绍率',
            dataIndex: 'referralRatio',
            render: rateRender
        }
    ]
);


function Personal(props) {
    const {title, desc, filter, viewName, match: {params: {id}}, searchValue, userRoundValue} = props;
    const [data, setData] = useState([]);
    const [total, setTotal] = useState();
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [loading, setLoading] = useState(false);
    const [downLoading, setDownLoading] = useState(false);
    const [columns, setColumns] = useState([]);
    const getParams = (pageSize = 10, pageNum = 1) => {
        const param = {
            viewName,
            permissions: searchValue.personalFilter,
            pager: {
                pageSize,
                pageNum
            },
            rounds: getReportRounds(Number(id)),
            dimensionAndValues: searchValue.dimensionAndValues,
            sortRule: searchValue.sortRule,
        };

        return param;
    };

    const search = (num = current, size = pageSize) => {
        const param = getParams(size, num);
        setLoading(true);
        personalSearch(param).then(res => {
            if (res.code === 0) {
                setData(res.data.personalSearchDTOList);
                setTotal(res.pager.count);
            }
        })
            .finally(() => {
                setLoading(false);
            });
    };

    const pagerChange = (page, size) => {
        const num = size !== pageSize ? 1 : page;
        setCurrent(num);
        setPageSize(size);
        search(num, size);
    };

    useEffect(() => {
        // 改变外部条件时，重置到第一页
        setCurrent(1);
        setPageSize(10);
        search(1, 10);
    }, [searchValue]);

    const handleDownload = () => {
        const param = getParams();
        setDownLoading(true);
        fetchPersonalDownload(param, () => setDownLoading(false));
    };

    return (
        <div className="personalTable">
            <div className="title-container">
                <h2>
                    {title}
                    <span className="desc">
                        <ExclamationCircleFilled />
                        {desc}
                    </span>
                </h2>
                {data.length > 0 && (
                    <Button
                        type="primary"
                        onClick={handleDownload}
                        loading={downLoading}
                    >
                        下载
                    </Button>
                )}
            </div>
            <Table
                rowKey={(record, index) => index}
                columns={columnsFn(userRoundValue)}
                dataSource={data}
                loading={loading}
                size="small"
                bordered
                scroll={{x: 'max-content'}}
                pagination={{
                    total,
                    current,
                    pageSize,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    onChange: pagerChange,
                    // onShowSizeChange: sizeChange
                }}
            />
        </div>
    );
}


export default withRouter(Personal);
